package com.zsk.shop.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsk.shop.common.base.BaseResponse;
import com.zsk.shop.common.constant.Constant;
import com.zsk.shop.common.utils.DateUtils;
import com.zsk.shop.common.utils.HttpContext;
import com.zsk.shop.common.utils.ToolUtil;
import com.zsk.shop.entity.VerificationImage;
import com.zsk.shop.mapper.VerificationImageMapper;
import com.zsk.shop.model.results.VerificationXYResults;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author ljh
 * @date 2021年6月21日
 */
@Service
public class VerificationImageService extends ServiceImpl<VerificationImageMapper, VerificationImage> {

    //短信失效时间为5分钟
    private final static Integer INVALID_TIME = 5;

    public static boolean rangeInDefined(int current, int min, int max) {
        return Math.max(min, current) == Math.min(current, max);
    }

    /**
     * @param id
     * @param result
     * @return 有值则为报错内容
     */
    public Map<String, String> h5CheckVerificationImage(Long id, String result) {
        Map<String, String> map = new HashMap<>(2);
        LambdaQueryWrapper<VerificationImage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VerificationImage::getId, id);
        queryWrapper.last("limit 1");
        VerificationImage verificationImage = getOne(queryWrapper);
        map.put("value", "验证码校验错误。");
        map.put("key", "501");
        if (ToolUtil.isEmpty(verificationImage)) {
            return map;
        }
        if(!HttpContext.getPlatform().equals(2)){
            Integer min = Integer.parseInt(verificationImage.getResult())-15;
            Integer max = Integer.parseInt(verificationImage.getResult())+20;
            if(!rangeInDefined(Integer.parseInt(result), min, max)){
                return map;
            }
        }else{
            if(!result.equals(verificationImage.getResult())){
                return map;
            }
        }
        if (verificationImage.getInvalidTime().compareTo(new Date()) <= 0) {
            map.put("value", "验证码已失效。");
            map.put("key", "502");
            return map;
        }
        if (ToolUtil.isNotEmpty(verificationImage.getUseTime())) {
            map.put("value", "验证码已使用。");
            map.put("key", "503");
            return map;
        }
        useVerificationImage(id);
        return new HashMap<>(2);
    }

    /**
     * @param id
     * @param result
     * @return 有值则为报错内容
     */
    public String checkVerificationImage(Long id, String result) {
        LambdaQueryWrapper<VerificationImage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VerificationImage::getId, id);
        queryWrapper.last("limit 1");
        VerificationImage verificationImage = getOne(queryWrapper);
        if (ToolUtil.isEmpty(verificationImage)) {
            return "验证码校验错误。";
        }
        if(!HttpContext.getPlatform().equals(2)){
            Integer min = Integer.parseInt(verificationImage.getResult())-15;
            Integer max = Integer.parseInt(verificationImage.getResult())+20;
            if(!rangeInDefined(Integer.parseInt(result), min, max)){
                return "验证码校验错误。";
            }
        }else{
            if(!result.equals(verificationImage.getResult())){
                return "验证码校验错误。";
            }
        }
        if (verificationImage.getInvalidTime().compareTo(new Date()) <= 0) {
            return "验证码已失效。";
        }
        if (ToolUtil.isNotEmpty(verificationImage.getUseTime())) {
            return "验证码已使用。";
        }
        useVerificationImage(id);
        return "";
    }

    public BaseResponse<VerificationXYResults> randXYPoint(){
        int x, y;
        Random random = new Random(System.currentTimeMillis());
        x = random.nextInt(99);
        y = random.nextInt(99);
        VerificationImage image = new VerificationImage();
        image.setContent(x+","+y);
        image.setResult(x+","+y);
        Random num = new Random();
        int fileName = num.nextInt(5)+1;
        String str = "https://oss.zhishangkeapp.com/captcha/image/"+fileName+".png";
        image.setUrl(str);
        image.setInvalidTime(DateUtils.addMinute(1));
        this.getBaseMapper().insertSelective(image);

        VerificationXYResults results = new VerificationXYResults();
        results.setContent(image.getContent());
        results.setInvalidTime(image.getInvalidTime());
        results.setUrl(image.getUrl());
        results.setId(image.getId());
        return BaseResponse.success(results);
    }


    public void useVerificationImage(Long id) {
        VerificationImage verificationImage = getById(id);
        verificationImage.setUseTime(new Date());
        saveOrUpdate(verificationImage);
    }

}
